package oa.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;


import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import oa.dao.ForumManageDao;
import oa.dao.base.impl.BaseDaoImpl;
import oa.domain.forum.Forum;


@Repository("forumManageDao")
public class ForumManageDaoImpl extends BaseDaoImpl<Forum> implements ForumManageDao {



	@Resource(name="hibernateTemplate")	
	public HibernateTemplate hibernateTemplate;
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<Forum> getAllEntry() {
		// TODO Auto-generated method stub
		return (Collection<Forum>)this.hibernateTemplate.find("from Forum f order by f.position");
	}

	/**
	 * 重写父类的保存方法，在保存的时候把position的值设置为id的值
	 */
	@Override
	public void saveEntity(Forum e) {
		// TODO Auto-generated method stub
		super.saveEntity(e);//由瞬时对象变为持久对象，id已经有值了
		e.setPosition(e.getId().intValue()); //设置position的值为id的值
	}

	@Override
	public void move(Serializable id,final String hql) {
		// TODO Auto-generated method stub
		Forum forum1 = getEntryById(id);
		final int pos1 = forum1.getPosition();	
		Forum forum2 = this.hibernateTemplate.execute(new HibernateCallback<Forum>() {
			@Override
			public Forum doInHibernate(Session sesison) throws HibernateException,
					SQLException {
				Query query = sesison.createQuery(hql);
				query.setParameter(0, pos1);
				query.setFirstResult(0);
				query.setMaxResults(1);
				return (Forum) query.uniqueResult();
				
				}
		});
	
		forum1.setPosition(forum2.getPosition());
		forum2.setPosition(pos1);
		
	}

}
